/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package LwuitUI;

/**
 *
 * @author anup.s
 */
import com.sun.lwuit.Image;
import com.sun.lwuit.TabbedPane;
import com.sun.lwuit.Display;
import com.sun.lwuit.Component;
import com.sun.lwuit.Label;


import lcduilwuit.Command;
import com.sun.lwuit.events.*;
import com.sun.lwuit.layouts.*;
import mujmail.*;
import mujmail.util.*;
import java.util.*;
import mujmail.account.*;
import com.sun.lwuit.List;
import com.sun.lwuit.list.*;
import com.sun.lwuit.plaf.*;
import javax.microedition.lcdui.AlertType;

//#ifdef MUJMAIL_SEARCH
import mujmail.search.SearchWindows;
//#endif

public class Menu extends lcduilwuit.Form implements ActionListener {
    Image imFolders, imSettings, imAccounts,imUtilities;
    static final Command defaultCmd = new Command("default");
    final Command retriveMailComamnd = new Command(Lang.get(Lang.AC_RETRIEVE_MAILS),4);
    final Command writeNewMail = new Command(Lang.get(Lang.AC_WRITE_MAIL),1);
    //#ifdef SONIMMAIL_CAMERA
    final Command sendSnap = new Command("Send photo",2);
    //#endif
    //#ifdef SONIMMAIL_VOICEMAIL
    final Command sendVmail = new Command("Send voicemail",3);
    //#endif
    final Command startPolling = new Command(Lang.get(Lang.EXTRA_START_POLLING),5);
    final Command stopPolling = new Command(Lang.get(Lang.EXTRA_STOP_POLLING),6);
    final Command sendAll = new Command(Lang.get(Lang.AC_SENDALL),7);

    private static final boolean DEBUG = false;
    MujMail mujMail;
    Command exit, cmdNew, change, delete, setPrimary, retrieve;//, clear;
    //#ifdef MUJMAIL_USR_FOLDERS
    /// User Folders commands
    Command fldAdd, fldEdit, fldDel;
    //#endif
    TabbedPane tp;
    List accList, folderList, settingsList, utilitiesList;
    static final int FOLDERS = 0;
    static final int SETTINGS = 1;
    static final int ACCOUNTS = 2;
    static final int UTILITIES = 3;
    List[] lists = new List[4];
    /*Vector*/FolderListModel folders;
    Vector accounts;
    ActionListener aListener = new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (ae.getCommand() == Menu.this.getDefaultCommand()) {
                mujMail.getAccountSettings().showAccount(getSelectedAccount());
            }
        }
    };
    SelectionListener folderSelectionListener = new SelectionListener() {

        public void selectionChanged(int oldSelected, int newSelected) {
            removeCommand(fldEdit);
            removeCommand(fldDel);
            if (newSelected >= 5) {
                addCommand(fldEdit);
                addCommand(fldDel);

            }


        }
    };
    public static Label focus = new Label("");
    public void addToFolderList(InBox box)
    {
        folders.addItem(box);
    }
    public Menu(mujmail.MujMail m) {
        super(Lang.get(Lang.EXTRA_SONIMAIL));
        setScrollable(false);
        focus.getStyle().setFgColor(0x42647F);
        focus.getStyle().setBgColor(0);//.setBgColor(0x42647F);
        focus.getStyle().setBgTransparency(128);
        mujMail = m;
        exit = new Command(Lang.get(Lang.BTN_EXIT), Command.EXIT, 0);
        cmdNew = new Command(Lang.get(Lang.BTN_AS_NEW), Command.ITEM, 1);
        change = new Command(Lang.get(Lang.BTN_EDIT), Command.ITEM, 2);
        delete = new Command(Lang.get(Lang.BTN_DELETE), Command.ITEM, 4);
        setPrimary = new Command(Lang.get(Lang.BTN_AS_SET_PRIMARY), Command.ITEM, 5);
        retrieve = new Command(Lang.get(Lang.BTN_RTV_NEW_MAILS), Command.ITEM, 0);
        //#ifdef MUJMAIL_USR_FOLDERS
        fldAdd = new Command(Lang.get(Lang.EXTRA_BTN_USR_FLD_ADD));
        fldDel = new Command(Lang.get(Lang.BTN_DELETE));
        fldEdit = new Command(Lang.get(Lang.BTN_EDIT));
        //#endif
          imFolders = Functions.getIcon("menu_folders.png");
        imSettings = Functions.getIcon("menu_settings.png");
        imAccounts = Functions.getIcon("menu_accounts.png");
        imUtilities = Functions.getIcon("menu_utilities.png");
        setLayout(new BorderLayout());
        tp = new TabbedPane();
        tp.setStyle(getStyle());
        tp.addTabsListener(new SelectionListener() {
            public void selectionChanged(int oldSelected, int newSelected) {
                if (newSelected == 2) {
                    reload();
                }
                setTabContext(newSelected);
            }
        });
        folders = new FolderListModel() ;//Vector/*<FolderMenuItem>*/(5);
        folders.addItem(new FolderMenuItem(Lang.get(Lang.TB_INBOX), MujMail.mujmail.getInBox()));
        folders.addItem(new FolderMenuItem(Lang.get(Lang.TB_OUTBOX), MujMail.mujmail.getOutBox()));
        folders.addItem(new FolderMenuItem(Lang.get(Lang.TB_SENTBOX), MujMail.mujmail.getSentBox()));
        folders.addItem(new FolderMenuItem(Lang.get(Lang.TB_DRAFT), MujMail.mujmail.getDraft()));
        folders.addItem(new FolderMenuItem(Lang.get(Lang.TB_TRASH), MujMail.mujmail.getTrash()));
        folderList = MenuRenderer.createList(folders, this, folderSelectionListener);
        folderList.setIsScrollVisible(true);

        settingsList = MenuRenderer.createList(new String[]{Lang.get(Lang.EXTRA_ML_MAIL_RETRIVIEVING_MAILS),
                    Lang.get(Lang.EXTRA_STORING_MAILS),
                    Lang.get(Lang.AC_POLLING),
                    //#ifdef SONIMMAIL_CAMERA
                    "Snapshot Settings",
                    //#endif
                    Lang.get(Lang.ST_OTHER)},
                    this);

        utilitiesList = MenuRenderer.createList(new String[]{Lang.get(Lang.AD_ADDRESSBOOK),
                    Lang.get(Lang.AC_CLEAR_DB),
                    //#ifdef MUJMAIL_SEARCH
                    Lang.get(Lang.EXTRA_AC_SEARCH_MAILS),
                    //#endif
                    Lang.get(Lang.ABT_ABOUT)}, this);

        accounts = new Vector/*<MailAccount>*/();
        Enumeration accts = mujMail.getMailAccounts().elements();
        while (accts.hasMoreElements()) {
            accounts.addElement(accts.nextElement());
        }
        accList = createList(accounts, new AccountsRenderer());
        lists = new List[]{folderList, settingsList, accList, utilitiesList};
        tp.addTab(Lang.get(Lang.TB_FOLDERS), imFolders, folderList);//folderContainer); /TB_FOLDERS
        tp.addTab( Lang.get(Lang.ST_SETTINGS), imSettings, settingsList); //ST_SETTINGS
        tp.addTab( Lang.get(Lang.AS_ACCOUNTS), imAccounts, accList);//*/accountContainer);
        tp.addTab(Lang.get(Lang.UT_UTILS), imUtilities, utilitiesList);
        addComponent("Center", tp);
        addCommand(exit);
        addCommand(cmdNew);
        addCommand(change);
        addCommand(delete);
        addCommand(setPrimary);
        addCommand(retrieve);
        addCommand(retriveMailComamnd);
        addCommand(writeNewMail);
        //#ifdef  SONIMMAIL_CAMERA
        addCommand(sendSnap);
        //#endif
        //#ifdef SONIMMAIL_VOICEMAIL
        addCommand(sendVmail);
        //#endif
        addCommand(sendAll);
        addCommand(startPolling);
        setTabContext(0);
        setCommandListener(this);
    }

    public void keyPressed(int keyCode) {
        int game = Display.getInstance().getGameAction(keyCode);
        if (game == Display.GAME_DOWN || game == Display.GAME_UP) {
            List l = lists[tp.getSelectedIndex()];
            if (!l.hasFocus()) {
                l.requestFocus();
            }/* else if (l.hasFocus() && ((l.getSelectedIndex() == 0 && game == Display.GAME_UP) || (l.getSelectedIndex() == l.size() - 1 && game == Display.GAME_DOWN))) {
                return;
            }*/
        } else if (game == Display.GAME_RIGHT || game == Display.GAME_LEFT) {
            if (!tp.hasFocus()) {
                tp.requestFocus();
            }

        } else if (game == Display.GAME_FIRE) {
            List l = lists[tp.getSelectedIndex()];
            if (!l.hasFocus()) {
                //System.out.print("REQUESTING FOCUS");
                l.requestFocus();
            }
        }
        super.keyPressed(keyCode);

    }

    public void reload() {
            switch (tp.getSelectedIndex()) {
            case FOLDERS:
                break;
            case ACCOUNTS:
                accounts.removeAllElements();
                Enumeration accts = mujMail.getMailAccounts().elements();
                while (accts.hasMoreElements()) {
                    accounts.addElement(accts.nextElement());
                }
               break;
        }
        revalidate();

    }

    public void onShow() {
        reload();
    }

    public String getSelectedAccount() {

        if (accList == null || accList.size() == 0) {
            return null;
        }
        MailAccount account = (MailAccount) accList.getSelectedItem();
        return account.getEmail();

    }

    public void refreshAll(boolean displayMenu) {
         if (displayMenu) {
            repaint();
            mujMail.getDisplay().setCurrent(this);
        }
    }

    public void refresh(byte tabContext, boolean displayMenu) {
        show();
    }

    public void setSelectedTab(byte newTab) {
    }

    public byte getSelectedTab() {
        return 0;
    }
    boolean isPolling = false;

    public void actionPerformed(ActionEvent evt) {
        if (evt.getCommand() == exit) {
            mujmail.tasks.TasksManager.conditionallyExit();
        }

        switch (tp.getSelectedIndex()) {

            case ACCOUNTS:
                Command c = (lcduilwuit.Command)evt.getCommand();

                if (c == cmdNew) {
                    mujMail.getAccountSettings().showAccount(null);
                //mujmail.account.AccountSettings.showNewAccountOption();
                } else if (c == change) {
                    mujMail.getAccountSettings().showAccount(getSelectedAccount());
                } else if (c == delete) {
                    mujMail.getAccountSettings().deleteAccount(getSelectedAccount(), false);
                } else if (c == setPrimary) {
                    String accountID = getSelectedAccount();
                    if (accountID != null && ((MailAccount) mujMail.getMailAccounts().get(accountID)).isActive()) {
                        Settings.primaryEmail = accountID;
                        mujMail.getSettings().saveSettings(true);
                    } else {
                        mujMail.alert.setAlert(null, this, Lang.get(Lang.ALRT_AS_NONEXIST), MyAlert.DEFAULT, AlertType.INFO);
                    }
                } else if (c == retrieve) {
                    mujMail.getDisplay().setCurrent(mujMail.getInBox());
                    mujMail.getInBox().retrieveOne(getSelectedAccount());
                } else if (c == defaultCmd) {
                    mujMail.getAccountSettings().showAccount(getSelectedAccount());
                }
                break;
            case SETTINGS:
                if (evt.getCommand() == defaultCmd) {

                    switch (settingsList.getSelectedIndex()) {
                        case 0:
                            mujMail.getSettings().showRetrievingSettingsForm();
                            break;
                        case 1:
                            mujMail.getSettings().showStoringMailsSettingsForm();
                            break;
                        case 2:
                            mujMail.getSettings().showPollingSettingsForm();
                            break;
                        case 3:
                            //#ifdef SONIMMAIL_CAMERA
                             mujMail.getSettings().showSnaphotSettingsForm();
                             break;
                        case 4:
                            //#endif
                            mujMail.getSettings().showOtherSettingsForm();
                            break;

                    }

                }
                break;
            case FOLDERS:
                if (evt.getCommand() == defaultCmd) {

                    switch (folderList.getSelectedIndex()) {
                        case 0:
                            mujMail.getInBox().showBox();
                            break;
                        case 1:
                            mujMail.getOutBox().showBox();
                            break;
                        case 2:
                            mujMail.getSentBox().showBox();
                            break;
                        case 3:
                            mujMail.getDraft().showBox();
                            break;
                        case 4:
                            mujMail.getTrash().showBox();
                            break;
                        default:
                            TheBox box = (TheBox) (folderList.getSelectedItem());
                            box.show();
                            break;
                    }

                } else if (evt.getCommand() == retriveMailComamnd) {
                    mujMail.getDisplay().setCurrent(mujMail.getInBox());
                    mujMail.getInBox().retrieve();
                } else if (evt.getCommand() == writeNewMail) {
                    new SendMail(mujMail).writeMail(this);
                    //#ifdef SONIMMAIL_CAMERA
                } else if (evt.getCommand() == sendSnap) {
                   new SnapshotForm(this, new SendMail(mujMail)).show();
                    //#endif
                   //#ifdef SONIMMAIL_VOICEMAIL
                }else if(evt.getCommand() ==sendVmail){
                     new SoundRecordForm(this, new SendMail(mujMail)).show();
                     //#endif
                } else if (evt.getCommand() == sendAll) {
                   // mujMail.getDisplay().setCurrent(mujMail.outBox);
                    mujMail.outBox.sendAll();
                } else if (evt.getCommand() == startPolling) {
                    isPolling = true;
                    removeCommand(startPolling);
                    addCommand(stopPolling);
              //      mujmail.ui.AudioAlert.loadSound();
                    mujMail.getInBox().poll();
                } else if (evt.getCommand() == stopPolling) {
                    isPolling = false;
                    removeCommand(stopPolling);
                    mujMail.getInBox().poll();
                    addCommand(startPolling);
              //       mujmail.ui.AudioAlert.unloadSound();
                } else if (evt.getCommand() == fldAdd) {
                    mujMail.getUserMailBoxes().createPersistentBox();
                } else if (evt.getCommand() == fldDel) {
                    mujMail.getUserMailBoxes().removeUserMailBox((InBox)folderList.getSelectedItem());
                    folders.removeItem(folderList.getSelectedIndex());
                } else if (evt.getCommand() == fldEdit) {
                    mujMail.getUserMailBoxes().editUserMailBoxSettings((InBox)folderList.getSelectedItem());
                }
                break;
            case UTILITIES:
                if (evt.getCommand() == defaultCmd) {

                    switch (utilitiesList.getSelectedIndex()) {
                        case 0:
                          //  mujMail.getDisplay().setCurrent(mujMail.getAddressBook());
                            new AddressBook(mujMail).show();
                            break;
                        case 1:
                            ClearDBSelect clearDBSelect = new ClearDBSelect();
                            clearDBSelect.refresh();
                            mujMail.getDisplay().setCurrent(clearDBSelect);
                            break;
//#ifdef MUJMAIL_SEARCH
                        case 2:
                            SearchWindows searchWindows = new SearchWindows(mujMail);
                            searchWindows.displaySearchWindow();
                            break;
                        case 3:
//#else
//#                             case 2:
//#endif
                            mujMail.getDisplay().setCurrent(new About(this));
                            break;

                    }
                }
                break;

        }
    }

    private void setTabContext(int currTab) {
        removeCommand(cmdNew);
        removeCommand(change);
        removeCommand(delete);
        removeCommand(setPrimary);
        removeCommand(retrieve);
        removeCommand(retriveMailComamnd);
        removeCommand(writeNewMail);
        //#ifdef SONIMMAIL_CAMERA
        removeCommand(sendSnap);
        //#endif
        //#ifdef SONIMMAIL_VOICEMAIL
        removeCommand(sendVmail);
        //#endif
        removeCommand(sendAll);
        removeCommand(startPolling);
        removeCommand(stopPolling);
        //#ifdef MUJMAIL_USR_FOLDERS
        removeCommand(fldAdd);
        ///   removeCommand(fldEdit);
        //   removeCommand(fldDel);
        //#endif
//        addCommand(select);
        switch (currTab) {
            case SETTINGS:
                // addCommand(change);
                //       removeCommand(select);
                break;
            case ACCOUNTS:
                //   removeCommand(select);
                if (!mujMail.getAccountSettings().isBusy()) {
                    addCommand(cmdNew);
                    if (!mujMail.getMailAccounts().isEmpty()) {
//                        addCommand(clear);
                        addCommand(change);
                        addCommand(delete);
                        addCommand(setPrimary);
                        addCommand(retrieve);
                    }
                }
                break;
            /*case UTILS:
            break;*/
            case FOLDERS:
                addCommand(retriveMailComamnd);
                addCommand(writeNewMail);
                //#ifdef SONIMMAIL_CAMERA
                addCommand(sendSnap);
                //#endif
                //#ifdef SONIMMAIL_VOICEMAIL
                addCommand(sendVmail);
                //#endif
                addCommand(sendAll);
                if (isPolling) {
                    addCommand(stopPolling);
                } else {
                    addCommand(startPolling);
                }

                //#ifdef MUJMAIL_USR_FOLDERS
                addCommand(fldAdd);

                //#endif
                break;
        }
    //lets refresh the tab, so we don't have to see old info (like the * of TheBox counters)
    //refresh(currTab, false);
    }

    private List createList(Vector vct, ListCellRenderer renderer) {
        List list = new List(vct);
        list.getStyle().setBgTransparency(0);
        list.setListCellRenderer(renderer);
        list.setOrientation(List.VERTICAL);
        list.setItemGap(1);
        list.setBorderGap(1);
        Style s = list.getStyle();
        //s.setPadding(0, 0, 0, 0);
        //s.setMargin(0, 0, 0, 0);
        s.setBorder(Border.createLineBorder(1));
        list.setStyle(s);
        list.addActionListener(aListener);
        list.setFixedSelection(List.FIXED_NONE_CYCLIC);
        return list;
    }
}



class FolderMenuItem {

    private String text;
    private TheBox box;

    public FolderMenuItem(String text, TheBox box) {
        this.text = text;
        this.box = box;
    }

    public TheBox getBox() {
        return box;
    }

    public String getText() {
        return text;
    }
}

class MenuRenderer /*extends Container*/ implements ListCellRenderer {

    Label item = new Label("");

    public MenuRenderer() {
        //  setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        //   addComponent(item);
    }

    public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected) {

        if (value instanceof FolderMenuItem) {
            StringBuffer text = new StringBuffer(((FolderMenuItem) value).getText());

            text.append(" (");
            TheBox box = ((FolderMenuItem) value).getBox();
            if (box instanceof InBox) {
                text.append(((InBox) box).getUnreadMailsCount() + "/");
            }

            text.append(box.getMessageCount() + ")");
            item.setText(text.toString());
        } else if (value instanceof TheBox) {
            StringBuffer text = new StringBuffer(((TheBox) value).getName());
            text.append(" (");
            text.append(((InBox) value).getUnreadMailsCount() + "/");
            text.append(((InBox) value).getMessageCount() + ")");
            item.setText(text.toString());

        } else if (value instanceof String) {
            item.setText((String) value);
        }
        item.getStyle().setBgTransparency(0);
        return item;
    }

    public Component getListFocusComponent(List list) {
        return Menu.focus;
    }

    public static List createList(ListModel items, final ActionListener al, SelectionListener sl) {
        List list = createList(items, al);
        list.addSelectionListener(sl);
        return list;
    }

    public static List createList(Object[] items, final ActionListener al) {
        return createList(new DefaultListModel(items), al);
    }

    public static List createList(ListModel dlm, final ActionListener al) {

        List list = new List(dlm) {

            public void keyReleased(int key) {
                int gameAction = com.sun.lwuit.Display.getInstance().getGameAction(key);
                if (gameAction == com.sun.lwuit.Display.GAME_FIRE) {
                    al.actionPerformed(new ActionEvent(Menu.defaultCmd));
                } else {
                    super.keyReleased(key);
                }
            }
            protected void modelChanged(int status,
                            int index)
            {
                //System.out.println("MODEL CHANGED");
            }
        };
        list.getStyle().setBgTransparency(0);
        list.setListCellRenderer(new MenuRenderer());
        list.setOrientation(List.VERTICAL);
        list.setFixedSelection(List.FIXED_NONE_CYCLIC);
        list.setItemGap(1);
        list.setBorderGap(1);
        Style s = list.getStyle();
        //s.setPadding(0, 0, 0, 0);
        //s.setMargin(0, 0, 0, 0);
        s.setBorder(Border.createLineBorder(1));
        list.setStyle(s);
        return list;
    }
}
 /// Shows about form
    class About extends lcduilwuit.Form implements ActionListener{
        Command back;//, feedBack;
        lcduilwuit.Form prevScreen;

        final  com.sun.lwuit.TextArea textArea = new com.sun.lwuit.TextArea(Lang.get(Lang.ABT_TEXT),5,5,com.sun.lwuit.TextArea.UNEDITABLE){
        public int getRows(){
            if(isGrowByContent()){
                return getLines();
            }else{
                return super.getRows();
            }
        }
        };
        public About(lcduilwuit.Form prevScreen) {
            super(Lang.get(Lang.ABT_ABOUT));
            this.prevScreen = prevScreen;
            setScrollable(false);
            Image logo = Functions.getIcon("logo.png");
            append(logo);
            addComponent(textArea);
            System.gc();
            addComponent(new  com.sun.lwuit.TextArea("Memory: "+Runtime.getRuntime().freeMemory()+"/"+Runtime.getRuntime().totalMemory()));
            back = new Command(Lang.get(Lang.BTN_BACK), Command.BACK, 0);
            addCommand(back);
            setCommandListener(this);
        }

        public void actionPerformed(ActionEvent evt) {
            if(evt.getCommand()==back)
            {
              prevScreen.show();
            }
        }

    }